package chapter1;

import java.util.Arrays;
import java.util.Random;

/**
 * 数组中三个数相加 =0的数对的个数
 */
public class ThreeSum {

    public static int count(int[] array) {

        Arrays.sort(array);

        int count = 0;
        for (int i = 0; i < array.length; i++) {
            for (int j = i + 1; j < array.length; j++) {

                int toSearch = -(array[i] + array[j]);
                int k = Arrays.binarySearch(array, j, array.length, toSearch);
                if (k > j) {
                    System.out.println("["+array[i]+","+array[j]+","+array[k]+"]");
                    count++;
                }
            }
        }
        return count;
    }

    public static void main(String[] args) {

        Random random = new Random();

        int[] arr = new int[100];
        for (int i = 0; i < 100; i++) {
            arr[i] = random.nextInt(200 + 1) - 100;
        }

        System.out.println(count(arr));
    }
}

